import {API_URL} from "../constants";

const ZOHO = window.ZOHO;

export async function getCrmFields(moduleName) {
    let req_data = {
        parameters: {},
        method: "GET",
        url: API_URL + `/crm/v3/settings/fields?module=${moduleName}&include=allowed_permissions_to_update`,
        param_type: 1,
    };
    let data = await ZOHO.CRM.CONNECTION.invoke("crm", req_data);
    return data.details.statusMessage.fields;
}

export async function getOptions(moduleName, fields = "id,Name") {
    if (moduleName === "Accounts") {
        fields = "id,Account_Name"
    }
    if (moduleName === "Products") {
        fields = "id,Product_Name"
    }
    let req_data = {
        parameters: {},
        method: "GET",
        url: API_URL + `/crm/v3/${moduleName}?fields=${fields}`,
        param_type: 1,
    };
    // let data = await ZOHO.CRM.CONNECTION.invoke("crm", req_data);
    let data = await ZOHO.CRM.API.getAllRecords({Entity: moduleName, sort_order: "asc", per_page: 200, page: 1});
    return data.data;
}

export async function getCrmRecordFromSql(sql) {
    let req_data = {
        "parameters": {
            "select_query": `${sql}`
        },
        "headers": {},
        "method": "POST",
        "url": `https://www.zohoapis.com.cn/crm/v4/coql`,
        "param_type": 2
    };
    let contact = await ZOHO.CRM.CONNECTION.invoke("crm", req_data);
    return contact.details.statusMessage.data;
}

export async function getCrmRecordById(moduleName, id) {
    let req_data = {
        "parameters": {},
        "headers": {},
        "method": "GET",
        "url": `https://www.zohoapis.com.cn/crm/v3/${moduleName}/${id}`,
        "param_type": 2
    };
    let contact = await ZOHO.CRM.CONNECTION.invoke("crm", req_data);
    return contact.details.statusMessage.data[0];
}

export async function getCrmProductsByParam(fields, typeArray, param) {
    let conditions = [];
    Object.entries(param).map(([key, value]) => {
        if (!isBlank(value)) {
            if (typeArray[key] === "text") {
                conditions.push(`${key} like '%${value}%'`);
            } else {
                conditions.push(`${key} = '${value}'`);
            }
        }
    });
    let combinedConditions = " id is not null ";
    if (conditions.length >= 2) {
        combinedConditions = `(${conditions[0]} and ${conditions[1]})`;
        for (let i = 2; i < conditions.length && conditions.length > 2; i++) {
            combinedConditions = `(${combinedConditions} and ${conditions[i]})`;
        }
    }
    if (conditions.length === 1) {
        combinedConditions = `${conditions[0]} `;
    }
    let sql = `select ${fields} from Products where ${combinedConditions}`;
    console.log(sql)
    return await getCrmRecordFromSql(sql);
}

export async function getCrmByParam(fields, typeArray, param, user, tablename) {
    let conditions = [];
    Object.entries(param).map(([key, value]) => {
        if (!isBlank(value)) {
            if (typeArray[key] === "text") {
                conditions.push(`${key} like '%${value}%'`);
            } else {
                conditions.push(`${key} = '${value}'`);
            }
        }
    });
    let combinedConditions = " id is not null ";
    if (conditions.length >= 2) {
        combinedConditions = `(${conditions[0]} and ${conditions[1]})`;
        for (let i = 2; i < conditions.length && conditions.length > 2; i++) {
            combinedConditions = `(${combinedConditions} and ${conditions[i]})`;
        }
    }
    if (conditions.length === 1) {
        combinedConditions = `${conditions[0]} `;
    }
    let sql = `select ${fields} from ${tablename} where ${combinedConditions}`;
    if (!isBlank(user)) {
        sql = `select ${fields} from ${tablename} where (${combinedConditions}) and Owner = ${user.id}`;
    }
    console.log(sql)
    return await getCrmRecordFromSql(sql);
}

export function isBlank(str) {
    return str === undefined || str === null || str === "";
}

//替换key
export function convertKey(arr, keyMap) {
    let tempString = JSON.stringify(arr);
    console.log('tempString', tempString);
    for (var key in keyMap) {
        var reg = new RegExp(`"${escapeRegExp(key)}":`, 'g');

        tempString = tempString.replaceAll("\\t", "").replace(reg, `"${keyMap[key]}":`);
    }
    return JSON.parse(tempString);
}

function escapeRegExp(string) {
    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

export function strIfNull(value) {
    if (value === null || value === undefined || value === "") {
        return "";
    }
    return value + "";
}

export function doubleIfNull(value) {
    if (value === null || value === undefined || value === "") {
        return 0.0000;
    }
    return parseFloat(value).toFixed(4)
}

export function intIfNull(value) {
    if (value === null || value === undefined || value === "") {
        return 0;
    }
    return parseInt(value)
}

export function isEmptyObject(value) {

}